package com.infra.micro.id.domain.repository;

import com.infra.micro.id.domain.entity.IdWorkerExample;
import com.infra.micro.id.domain.entity.IdWorkerPO;
import com.infra.micro.id.domain.mapper.IdWorkerMapper;
import com.infra.micro.id.model.req.QueryIdWorkerByCondReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class IdWorkerRepository {
    @Resource
    private IdWorkerMapper idWorkerMapper;

    public int insert(IdWorkerPO record) {
        return idWorkerMapper.insertSelective(record);
    }

    public List<IdWorkerPO> queryList(QueryIdWorkerByCondReq req) {
        IdWorkerExample example = new IdWorkerExample();
        IdWorkerExample.Criteria criteria = example.createCriteria();
        if (req.getWorkerId() != null) {
            criteria.andWorkerIdEqualTo(req.getWorkerId());
        }
        if (StringUtils.isNotBlank(req.getKey())) {
            criteria.andLocalhostLike("%" + req.getKey() + "%");
        }

        return idWorkerMapper.selectByExample(example);
    }

    public int updateMaxTimestamp(int workerId, long currentTime) {
        IdWorkerPO record = new IdWorkerPO();
        record.setWorkerId(workerId);
        record.setMaxTimestamp(currentTime);
        return idWorkerMapper.updateByPrimaryKeySelective(record);
    }

    public IdWorkerPO queryByCond(String ip, Integer port) {
        IdWorkerExample example = new IdWorkerExample();
        example.createCriteria().andIpEqualTo(ip).andPortEqualTo(port);
        return idWorkerMapper.selectByExample(example).stream().findFirst().orElse(null);
    }
}
